<?php

namespace App\Utility;


use EasySwoole\Spl\SplString;
use EasySwoole\HttpClient\HttpClient;

class Music{

    protected $apis = [
        'base' => 'https://u.y.qq.com/cgi-bin/musicu.fcg?',
        'link' => 'http://dl.stream.qqmusic.qq.com/',
    ];

    /**
     * 获取音乐的guid
     * @return int
     */
    protected function getGuid(){
        list($u, $s) = explode(" ", microtime());
        $m = round($u * 1000);
        $guid = round((mt_rand()/mt_getrandmax())*2147483647) * $m % 10000000000;
        return $guid;
    }

    /**
     * 获取音乐播放地址
     * @param string $songmid
     * @return bool|string
     */
    public function getMusic($songmid = ''){
        if(!$songmid) return false;
        $guid = $this->getGuid();
        $params = [
            'g_tk' => 5381,
            'loginUin' => 0,
            'hostUin' => 0,
            'format' => 'json',
            'inCharset' => 'utf8',
            'outCharset' => 'utf-8',
            'notice' => 0,
            'platform' => 'yqq.json',
            'needNewCode' => 0,
            'data' => '{"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"'.$guid.'","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"'.$guid.'","songmid":["'.$songmid.'"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}},"comm":{"uin":0,"format":"json","ct":20,"cv":0}}',
        ];
        $header = [
            ':authority' => 'u.y.qq.com',
            ':method' => 'GET',
            ':scheme' => 'https',
            'referer' => 'https://u.y.qq.com/',
            'origin' => 'https://u.y.qq.com/',
        ];
        $result = $this->sendRequest('GET',$this->apis['base'],$params,$header);
        if(count($result['req_0']['data']['midurlinfo'])){
            return $this->apis['link'].$result['req_0']['data']['midurlinfo']['0']['purl'];
        }
        return false;
    }

    /**
     * send a http request
     * @param string $method
     * @param string $url
     * @param null $params
     * @param null $header
     * @return mixed
     */
    protected function sendRequest(string $method='GET',string $url='', $params=null, $header=null){
        if($method == 'GET') $url .= http_build_query($params);
        $request = new HttpClient($url);
        if($method == 'POST')  $request->postJSON($params);
        if($header) $request->setHeaders($header);
        $result = $request->exec();
        $string = new SplString($result->getBody());
        return json_decode($string, true);
    }

}
